import React from 'react';
import routes from './routes';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, message} from 'antd';
import {PERMISSION} from './constants';
import {FORM_OPTIONS} from '../constants';
import {hasPermissions} from './utils';
import {injectIntl, language} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import {salePlanStatus} from '../Enum';
import TagSelect from 'Shared/components/TagSelect';
import WrappedInputNumber from '../common/WrappedInputNumber';
import Export from '../common/Export';
import SearchSelectPanel from '../common/DutyUnitSelect/SelectEdit';
import ImportPanel from './ImportPanel';
import {getMarketDepartment, getMarketDepartmentSimple, getManufacturerSimple, getManufacturer} from './api';
const FormItem = Form.Item;
const statusList = salePlanStatus.toList(language);
class QueryPanel extends React.PureComponent {
    state = {
        showImport: false
    }
    handleFilterChange = (value, name) => {
        this.props.onChange(name, value);
    }
    handleFilterPressEnter = (value, name) => {
        this.props.onChange(name, value);
        this.props.querySearch();
    }
    onImportChange = data => {
        if(data) {
            this.setState({showImport: false});
            message.success(this.props.intl.formatMessage({
                id: 'queryPanel.msg.batchImport',
                defaultMessage: '批量导入成功'
            }));
            this.props.querySearch();
        }
    }
    onClickImport = () => this.setState({showImport: true});
    onCloseImport = () => this.setState({showImport: false});
    
    onClickSubmit = () => {
        this.props.onChange('status', [salePlanStatus.新建]);
        this.props.querySearch();
        this.props.onClickSubmitBtn();
    }
    onClickAbandon = () => {
        this.props.onChange('status', [salePlanStatus.新建]);
        this.props.querySearch();
        this.props.onClickAbandonBtn();
    }
    render() {
        const operations = [];
        const {formatMessage} = this.props.intl;
        if(hasPermissions(this.props.permissions, PERMISSION.export) && (!this.props.isShowAbandonPanel && !this.props.isShowSubmitPanel))
            operations.push(<Export key={PERMISSION.export} exportRequest={this.props.exportData} />);
        if(hasPermissions(this.props.permissions, PERMISSION.submit) && (!this.props.isShowAbandonPanel && !this.props.isShowSubmitPanel))
            operations.push(<Button key="submit" onClick={this.onClickSubmit}>{formatMessage({
                id: 'queryPanel.btn.submit',
                defaultMessage: '批量生效'
            })}</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && (!this.props.isShowAbandonPanel && !this.props.isShowSubmitPanel))
            operations.push(<Button key="abandon" onClick={this.onClickAbandon}>{formatMessage({
                id: 'queryPanel.btn.abandon',
                defaultMessage: '批量作废'
            })}</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.import) && (!this.props.isShowAbandonPanel && !this.props.isShowSubmitPanel))
            operations.push(<Button key="import" type="primary" onClick={this.onClickImport}>
                {formatMessage({
                    id: 'queryPanel.btn.import',
                    defaultMessage: '批量导入'
                })}</Button>);
        const dealerInfo = this.props.condition.dealerId ? {
            id: this.props.condition.dealerId,
            code: this.props.condition.dealerCode,
            name: this.props.condition.dealerName
        } : null;
        const manufacturerInfo = this.props.condition.manufacturerId ? {
            id: this.props.condition.manufacturerId,
            name: this.props.condition.manufacturerName
        } : null;
        const markeInfo = this.props.condition.marketDepartmentId ? {
            id: this.props.condition.marketDepartmentId,
            name: this.props.condition.marketDepartmentName
        } : null;
        return (
            <div>
                <Form className="form-standard">
                    <Row>
                        {this.props.brands.length !== 1 && <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.brand',
                                    defaultMessage: '品牌'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="brandId"
                                    value={this.props.condition.brandId}
                                    options={this.props.brands}
                                    onChange={this.handleFilterChange}/>
                            </FormItem>
                        </Col>}
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={formatMessage({
                                    id: 'queryPanel.form.marketDepartmentId',
                                    defaultMessage: '大区'
                                })}
                                {...FORM_OPTIONS.item}>
                                <SearchSelectPanel
                                    value={markeInfo}
                                    getDutyUnits={getMarketDepartment}
                                    getDutyUnitSimple={getMarketDepartmentSimple}
                                    titleName={formatMessage({
                                        id: 'queryPanel.form.marketDepartmentId',
                                        defaultMessage: '大区'
                                    })}
                                    isLabelMap={false}
                                    onSelect={this.props.onSelectMarke} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={formatMessage({
                                    id: 'queryPanel.form.dealerId',
                                    defaultMessage: '总代'
                                })}
                                {...FORM_OPTIONS.item}>
                                <DealerSelectPanel
                                    value={dealerInfo}
                                    onSelect={this.props.onSelectDealer} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={formatMessage({
                                    id: 'queryPanel.form.manufacturerId',
                                    defaultMessage: '生产工厂'
                                })}
                                {...FORM_OPTIONS.item}>
                                <SearchSelectPanel
                                    value={manufacturerInfo}
                                    getDutyUnits={getManufacturer}
                                    getDutyUnitSimple={getManufacturerSimple}
                                    titleName={formatMessage({
                                        id: 'queryPanel.form.manufacturerId',
                                        defaultMessage: '生产工厂'
                                    })}
                                    isLabelMap={false}
                                    onSelect={this.props.onSelectManufacturer} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={formatMessage({
                                    id: 'queryPanel.form.submitYear',
                                    defaultMessage: '提报年份'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedInputNumber
                                    min={0}
                                    precision={0}
                                    name="submitYear"
                                    value={this.props.condition.submitYear}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={formatMessage({
                                    id: 'queryPanel.form.submitMonth',
                                    defaultMessage: '提报月份'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedInputNumber
                                    name="submitMonth"
                                    value={this.props.condition.submitMonth}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.status',
                                defaultMessage: '状态'
                            })} {...FORM_OPTIONS.item}>
                                <TagSelect
                                    name="status"
                                    value={this.props.condition.status}
                                    options={statusList}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={6}>
                            <Button key="query" type="primary"
                                onClick={this.props.querySearch} loading={this.props.loading}>
                                {formatMessage({
                                    id: 'queryPanel.btn.search',
                                    defaultMessage: '查询'
                                })}</Button>
                            <Button key="clear" onClick={this.props.onClickReset}>{formatMessage({
                                id: 'queryPanel.btn.reset',
                                defaultMessage: '重置'
                            })}</Button>
                        </Col>
                        <Col span={18} className="col-align-right">
                            {operations}
                        </Col>
                    </Row>
                </Form>
                {this.state.showImport &&
                    <ImportPanel
                        selectKey="showImport"
                        onCancel={this.onCloseImport}
                        onImportChange={this.onImportChange} />
                }
            </div>
        );
    }
}

QueryPanel.propTypes = {
    brands: PropTypes.array.isRequired,
    condition: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    querySearch: PropTypes.func.isRequired,
    onChange: PropTypes.func.isRequired,
    onClickAbandonBtn: PropTypes.func.isRequired,
    onClickReset: PropTypes.func.isRequired,
    onClickSubmitBtn: PropTypes.func.isRequired,
    onSelectDealer: PropTypes.func.isRequired,
    onSelectManufacturer: PropTypes.func.isRequired,
    onSelectMarke: PropTypes.func.isRequired,
    exportData: PropTypes.func,
    isShowAbandonPanel: PropTypes.bool,
    isShowSubmitPanel: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    saveQueryCondition,
    querySearch,
    resetQueryPanel,
    selectDealerQuery,
    exportData,
    selectMarkeQuery,
    startSubmit,
    startAbandon,
    selectManufacturerQuery
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getBrands = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'brands']),
    data => {
        const brands = data.toJS();
        return brands
            ? brands.map(item => ({
                value: item.id,
                text: `(${item.code})${item.name}`
            }))
            : [];
    }
);
const mapStateToProps = state => ({
    condition: getConditions(state),
    loading: state.getIn((['page', 'domainData', 'list', 'isFetching'])),
    permissions: getPermissions(state),
    brands: getBrands(state),
    isShowAbandonPanel: state.getIn(['page', 'ui', 'showAbandonPanel']),
    isShowSubmitPanel: state.getIn(['page', 'ui', 'showSubmitPanel']),
});

const mapDispatchToProps = dispatch => ({
    onChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    querySearch: () => dispatch(querySearch()),
    onClickReset: () => dispatch(resetQueryPanel()),
    onSelectDealer: data => dispatch(selectDealerQuery(data)),
    onSelectMarke: data => dispatch(selectMarkeQuery(data)),
    onSelectManufacturer: data => dispatch(selectManufacturerQuery(data)),
    exportData: () => dispatch(exportData()),
    onClickSubmitBtn: () => dispatch(startSubmit()),
    onClickAbandonBtn: () => dispatch(startAbandon()),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(QueryPanel));
